package com.java.jvm.memory;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

 class Obj{
    public void doSay(){
        System.out.println("Hello CGLIB");
    }
}
//模拟类太多了，导致方法区内存溢出
//-XX:MetaspaceSize=10M -XX:MaxMetaspaceSize=10M -XX:+PrintGC
public class ManyClassTests {
    public static void main(String[] args) {
        while (true) {//内部代码在位Obj类型创建子类(底层是CGLIB代理)
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(Obj.class);
            enhancer.setUseCache(false);//每次创建新代理对象
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    System.out.println("start");
                    Object result=methodProxy.invokeSuper(o, objects);//执行目标方法
                    System.out.println("end");
                    return result;
                }
            });
            //创建代对象(CGLIB)
            Obj instance=(Obj)enhancer.create();
            instance.doSay();
        }
    }
}

